import hashlib
import time

from flask import Flask, url_for, request, Blueprint, render_template, send_from_directory, flash, jsonify, redirect

from flaskr import *
from flaskr.db import get_db
from flaskr import user
from flaskr import model

bp = Blueprint('records', __name__, url_prefix='/records')


def get_records(main_no, sub_no, burn_result, datetime_begin, datetime_end, chip_uid):
    db = get_db()

    where_names = ''
    where_values = ()
    if main_no is not None and main_no != '':
        if where_names == '':
            where_names = ' WHERE {}=?'.format('prod_mainmodel')
        else:
            where_names += ' AND {}=?'.format('prod_mainmodel')
        where_values += (main_no,)

    if sub_no is not None and sub_no != '':
        if where_names == '':
            where_names = ' WHERE {}?'.format('prod_submodel')
        else:
            where_names += ' AND {}=?'.format('prod_submodel')
        where_values += (sub_no,)

    if burn_result is not None and burn_result != '':
        if where_names == '':
            where_names = ' WHERE {} LIKE ?'.format('burn_result')
        else:
            where_names += ' AND {} LIKE ?'.format('burn_result')
        where_values += ('%'+burn_result+'%',)

    if datetime_begin is not None and datetime_begin != '':
        if where_names == '':
            where_names = ' WHERE {}>=?'.format('date_time')
        else:
            where_names += ' AND {}>=?'.format('date_time')
        where_values += (datetime_begin,)

    if datetime_end is not None and datetime_end != '':
        if where_names == '':
            where_names = ' WHERE {}<=?'.format('date_time')
        else:
            where_names += ' AND {}<=?'.format('date_time')
        where_values += (datetime_end,)

    if chip_uid is not None and chip_uid != '':
        if where_names == '':
            where_names = ' WHERE {}=?'.format('chip_uid')
        else:
            where_names += ' AND {}=?'.format('chip_uid')
        where_values += (chip_uid,)

    query_str = "SELECT * FROM burn_records{}".format(where_names)
    rs = db.execute(query_str, where_values).fetchall()

    records = []
    for r in rs:
        record = {}
        record['account'] = r['account']
        record['tool_name'] = r['tool_name']
        record['tool_version'] = r['tool_version']
        record['tool_ip'] = r['tool_ip']
        record['prod_mainmodel'] = r['prod_mainmodel']
        record['prod_submodel'] = r['prod_submodel']
        record['prod_duid'] = r['prod_duid']
        record['prod_mac'] = r['prod_mac']
        record['fw_name'] = r['fw_name']
        record['fw_version'] = r['fw_version']
        record['fw_checksum'] = r['fw_checksum']
        record['fw_type'] = r['fw_type']
        record['fw_status'] = r['fw_status']
        record['burn_result'] = r['burn_result']
        record['datetime'] = r['date_time']
        record['chip_uid'] = r['chip_uid']
        records.append(record)

    return records


def add_record(account, tool_name,tool_version,tool_ip, prod_mainmodel, prod_submodel, prod_mac, prod_duid, fw_name, fw_version, fw_checksum, fw_type, fw_status, burn_result, chip_uid):
    try:
        db = get_db()
        db.execute(
            'INSERT INTO burn_records (account, tool_name, tool_version, tool_ip, prod_mainmodel, prod_submodel, prod_mac, '
            'prod_duid, fw_name, fw_version, fw_checksum, fw_type, fw_status, burn_result, date_time, chip_uid) VALUES (?, ?, ?, '
            '?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime("now", "localtime"), ?)', (account, tool_name, tool_version, tool_ip,
                                                                         prod_mainmodel, prod_submodel, prod_mac,
                                                                         prod_duid, fw_name, fw_version, fw_checksum,
                                                                         fw_type, fw_status, burn_result, chip_uid))
        db.commit()
        return True
    except Exception as e:
        return False


@bp.route('/', methods=('get', 'post'))
@bp.route('/entry', methods=('get', 'post'))
@user.login_required_as_super_ret("")
def entry():
    records = []
    if request.method == 'POST':
        action = request.form.get('action')
        main_no = request.form.get('main_no')
        sub_no = request.form.get('sub_no')
        burn_result = request.form.get('burn_result')
        datetime_begin = request.form.get('datetime_begin')
        datetime_end = request.form.get('datetime_end')
        chip_uid = request.form.get('chip_uid')

        if action == 'query':
            records = get_records(main_no, sub_no, burn_result, datetime_begin, datetime_end, chip_uid)

    return render_template('/records/entry.html',
                           records=records)



@bp.route('/simple_query', methods=('post',))
@user.login_required_ret(nologin="failed")
def simple_query():
    main_no = request.form.get('main_no')
    sub_no = request.form.get('sub_no')
    burn_result = request.form.get('burn_result')
    datetime_begin = request.form.get('datetime_begin')
    datetime_end = request.form.get('datetime_end')

    burn_list = get_records(main_no, sub_no, burn_result, datetime_begin, datetime_end)
    return jsonify(burn_list)

@bp.route('/simple_add_record', methods=('post',))
@user.login_required_ret(nologin="failed")
def simple_add_record():
    tool_name = request.form.get('tool_name')
    tool_version = request.form.get('tool_version')
    tool_ip = request.form.get('tool_ip')
    prod_mainmodel = request.form.get('prod_mainmodel')
    prod_submodel = request.form.get('prod_submodel')
    prod_duid = request.form.get('prod_duid')
    prod_mac = request.form.get('prod_mac')
    fw_name = request.form.get('fw_name')
    fw_version = request.form.get('fw_version')
    fw_checksum = request.form.get('fw_checksum')
    fw_type = request.form.get('fw_type')
    fw_status = request.form.get('fw_status')
    burn_result = request.form.get('burn_result')
    datetime = request.form.get('datetime')
    chip_uid = request.form.get('chip_uid')
    account = user.get_logged_username()

    add_record(account, tool_name,tool_version,tool_ip,prod_mainmodel, prod_submodel, prod_mac, prod_duid, fw_name, fw_version, fw_checksum, fw_type, fw_status, burn_result, chip_uid)
    return jsonify({"result": 'ok'})
